package com.xu.cloud.common.advice;

import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.pojo.Result;
import com.xu.cloud.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回值包装后置通知处理器
 *
 * @author xuguan
 * @since 2023/4/15
 * @see com.xu.cloud.common.pojo.Result
 */
@Order(OrderConstant.XU_CLOUD_WRAPPER_RESPONSE_BODY_ADVICE_ORDER)
@Slf4j
@RestControllerAdvice(basePackages = {"com.xu"})
public class XuCloudWrapperResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return Result.ok(null);
        } else if (body instanceof Result) {
            return body;
        } else if (body instanceof String) {
            return JsonUtil.toJsonString(Result.ok(body));
        } else {
            return Result.ok(body);
        }
    }
}
